<?php

/**
 * This is the model class for table "registration".
 *
 * The followings are the available columns in table 'registration':
 * @property integer $_id
 * @property integer $insertTime
 * @property integer $updateTime
 * @property string $name
 * @property string $birthPlace
 * @property integer $birthDate
 * @property string $homeAddress
 * @property string $homeCityType
 * @property string $homeCity
 * @property string $province
 * @property string $secretariatAddress
 * @property string $secretariatCityType
 * @property string $secretariatCity
 * @property string $emails
 * @property string $phones
 * @property string $position
 * @property string(4) $extension
 * @property string(16) $envoy
 * @property string $envoyProvince
 * @property string $envoyCity
 */
class Registration extends ActiveRecord {
	const CITY_TYPE_REGENCY = 'Kabupaten';
	const CITY_TYPE_MUNICIPALITY = 'Kota';
	const ENVOY_PROVINCE = 'Propinsi';
	const ENVOY_REGENCY = 'Kabupaten';
	const ENVOY_MUNICIPALITY = 'Kota';

	public $file;
	public $beginDate;
	public $endDate;
	public $birthDay;
	public $birthMonth;
	public $birthYear;

	/**
	 * Returns the static model of the specified AR class.
	 * @return Registration the static model class
	 */
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'registration';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array(
				'name, birthDate, birthPlace, envoy, envoyProvince, ' .
				'homeAddress, homeCityType, homeCity, province, phones',
				'required',
				'on'=>'insert, update',
			),
			array(
				'name, birthPlace, homeCityType, homeCity, province, ' .
				'emails, phones, position, envoyProvince, envoyCity',
				'length',
				'max'=>255,
				'on'=>'insert, update',
			),
			array(
				'province, envoyProvince',
				'exist',
				'className'=>'Province',
				'attributeName'=>'name',
				'on'=>'insert, update',
			),
			array(
				'homeCity, envoyCity',
				'exist',
				'className'=>'City',
				'attributeName'=>'name',
				'on'=>'insert, update',
			),
			array(
				'birthDate',
				'date',
				'format'=>'yyyy-M-d',
				'on'=>'insert, update'
			),
			array(
				'beginDate, endDate',
				'date',
				'format'=>'yyyy-M-d',
				'on'=>'download'
			),
			array(
				'birthDay, birthMonth, birthYear',
				'numerical',
				'integerOnly'=>true,
				'on'=>'insert, update'
			),
			array(
				'envoy',
				'application.extensions.YiiConditionalValidator',
				'validation'=>array(
					'in',
					'range'=>array(
						self::ENVOY_REGENCY,
						self::ENVOY_MUNICIPALITY
					)
				),
				'dependentValidations'=>array(
					'envoyCity'=>array(
						array('required'),
					),
				),
				'on'=>'insert, update'
			),
			array(
				'file',
				'file',
				'types'=>'jpg, jpeg, gif, png',
				'maxSize'=>10485760,
				'on'=>'insert',
			),
			array(
				'file',
				'file',
				'types'=>'jpg, jpeg, gif, png',
				'maxSize'=>10485760,
				'allowEmpty'=>true,
				'on'=>'update',
			),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array(
				'name, birthPlace, birthDate, homeAddress, homeCityType, ' .
				'homeCity, province, emails, phones, position',
				'safe',
				'on'=>'search'
			),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'file'=>'Pas Foto',
			'name'=>'Nama',
			'birthPlace'=>'Tempat Lahir',
			'birthDate'=>'Tanggal Lahir',
			'homeAddress'=>'Alamat',
			'homeCityType'=>'Type Kota/Kab',
			'homeCity'=>'Kota/Kab',
			'province'=>'Propinsi',
			'secretariatAddress'=>'Alamat',
			'secretariatCityType'=>'Type Kota/Kab',
			'secretariatCity'=>'Kota/Kab',
			'emails'=>'Email',
			'phones'=>'Telepon / Handphone',
			'position'=>'Jabatan',
			'envoy'=>'Utusan',
			'envoyProvince'=>'Propinsi',
			'envoyCity'=>'Kota/Kab',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('name', $this->name, true);

		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
			));
	}

	public function getCityTypeList() {
		return array(
			self::CITY_TYPE_MUNICIPALITY=>self::CITY_TYPE_MUNICIPALITY,
			self::CITY_TYPE_REGENCY=>self::CITY_TYPE_REGENCY,
		);
	}

	public function getEnvoyList() {
		return array(
			self::ENVOY_PROVINCE=>self::ENVOY_PROVINCE,
			self::ENVOY_REGENCY=>self::ENVOY_REGENCY,
			self::ENVOY_MUNICIPALITY=>self::ENVOY_MUNICIPALITY,
		);
	}

	/**
	 * @return boolean
	 */
	protected function beforeSave() {
		$this->file = CUploadedFile::getInstance($this, 'file');
		$this->birthDate = strtotime($this->birthDate);
		if ($this->file) {
			$info = getimagesize($this->file->tempName);
			if ($info[0] > 435) {
				$this->extension = 'jpg';
			} else {
				$this->extension = strtolower($this->file->extensionName);
			}
		}
		return parent::beforeSave();
	}

	protected function afterFind() {
		parent::afterFind();
		$this->birthDate = date('Y-n-j', $this->birthDate);
		$folder = Yii::app()->params['file'] . '/registration';
		$thumbnailPath = "{$folder}/thumbnail/{$this->_id}.jpg";
		if (!file_exists($thumbnailPath)) {
			$this->createThumbnail();
		}
	}

	protected function afterSave() {
		parent::afterSave();
		if ($this->file) {
			// We must save the uploaded file here because filename is_id
			// and _id only exist after saving.
			$folder = Yii::app()->params['file'] . '/registration';
			$path = "{$folder}/{$this->_id}.{$this->extension}";
			$info = getimagesize($this->file->tempName);
			if ($info[0] > 435) {
				$behavior = new EUploadedFileBehavior;
				$this->file->attachBehavior('saveAsJpg', $behavior);
				$this->file->saveAsJpeg($path, 435);
			} else {
				$this->file->saveAs($path);
			}
			$this->createThumbnail();
		}
	}

	protected function beforeValidate() {
		if ($this->envoy == self::ENVOY_PROVINCE) $this->envoyCity = null;
		$year = $this->birthYear;
		if ($year) {
			$this->birthDate = "$year-$this->birthMonth-$this->birthDay";
		}
		return parent::beforeValidate();
	}
	
	public function createThumbnail() {
		$folder = Yii::app()->params['file'] . '/registration';
		$path = "{$folder}/{$this->_id}.{$this->extension}";
		$imageFile = new ImageFile($path);
		$thumbnailPath = "{$folder}/thumbnail/{$this->_id}.jpg";
		$imageFile->saveAsJpeg($thumbnailPath, 100);
	}
	
}